package com.chenxbook.modules.jbpm4.assign;

import com.chenxbook.modules.boot.exception.GlobalException;
import com.chenxbook.modules.boot.web.enums.GlobalResponseEnum;
import lombok.Data;
import org.jbpm.api.*;
import org.jbpm.api.cmd.Environment;
import org.jbpm.pvm.internal.cmd.AbstractCommand;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.model.ProcessDefinitionImpl;
import org.jbpm.pvm.internal.model.TransitionImpl;
import org.jbpm.pvm.internal.task.TaskImpl;

import java.util.Map;

/**
 * <p>className: JumpTaskCommand</p>
 * <p>description: 工作流任务跳转命令</p>
 *
 * <br>
 *
 * @author chenxbook
 * @version 1.0.0
 * @date 2020-05-24 16:42
 */
@Data
public class JumpTaskCommand extends AbstractCommand<Void> {

    private static final long serialVersionUID = 1L;
    protected String taskId;
    protected String targetName;
    protected Map<String, ?> variables;

    @Override
    public Void execute(Environment environment) {
        //从流程引擎环境中获取执行、任务、历史3中服务
        ExecutionService executionService = environment.get(ExecutionService.class);
        TaskService taskService = environment.get(TaskService.class);
        TaskImpl currentTask = (TaskImpl) taskService.getTask(this.taskId);
        //获取流程实例
        ProcessInstance pi = executionService.findProcessInstanceById(currentTask.getProcessInstance().getId());
        //获取流程定义ID
        String processDefinitionId = pi.getProcessDefinitionId();
        RepositoryService repositoryService = environment.get(RepositoryService.class);
        //获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).uniqueResult();
        ProcessDefinitionImpl pd = (ProcessDefinitionImpl) processDefinition;
        ExecutionImpl exec = currentTask.getProcessInstance();
        //获取当前节点活动
        ActivityImpl currentActivity = exec.getActivity();
        //获取目标节点活动
        ActivityImpl sourceActivity = pd.findActivity(this.targetName);
        //如果目标节点找不到，不允许跳转
        if (sourceActivity == null) {
            throw new GlobalException(GlobalResponseEnum.QUERY_NOT_FOUND, "查询不到目标节点。。。");
        } else {
            //为跳转动态创建一条转移路径
            TransitionImpl newTransition = currentActivity.createOutgoingTransition();
            //跳转路径
            String transitionPath = String.join("", "jump  from ", currentActivity.getName(), " to ", sourceActivity.getName());
            newTransition.setSource(currentActivity);
            newTransition.setDestination(sourceActivity);
            newTransition.setName(transitionPath);
            taskService.completeTask(this.taskId, transitionPath, this.variables);
            //清除当前节点的刚创建的转移路径
            currentActivity.removeOutgoingTransition(newTransition);
            return null;
        }
    }


}